<!-- 快速发起 -->
<template>
  <div>
    <div class="title">
      <div style="display: flex; justify-content: space-between">
        <h3>快速发起</h3>
        <a-button
          type="primary"
          style="padding: 0 10px"
          @click="visible = true"
        >
          <svg
            class="icon"
            aria-hidden="true"
            style="font-size: 14px; margin-right: 4px"
          >
            <use xlink:href="#icon-tianjia"></use>
          </svg>
          发起任务
        </a-button>
      </div>
      <div>
        <template v-if="loading">
          <a-spin :loading="true">
            <div style="height: 60px"></div>
          </a-spin>
        </template>
        <template v-else>
          <template v-if="cardListData && cardListData.length > 0">
            <ul>
              <li
                v-for="(itm, index) in cardListData?.slice(0, 6)"
                :key="index"
                style="cursor: pointer"
                @click="workflowRun(itm, index)"
              >
                <svg
                  v-if="itm.icon && itm.icon.startsWith('icon')"
                  class="icon"
                  aria-hidden="true"
                  style="font-size: 32px"
                >
                  <use :xlink:href="`#${itm.icon}`"></use>
                </svg>
                <img
                  v-else
                  style="width: 32px; height: 32px"
                  :src="require(`@/assets/${itm.icon || 'default'}.png`)"
                />
                <a-spin :loading="itm.spinning ? itm.spinning : false">
                  <div class="ellipsis-text">
                    <OverflowText :text="itm.modelName ?? ''" :maxWidth="'150px'" />
                  </div>
                </a-spin>
              </li>
            </ul>
          </template>
          <template v-else>
            <div style="display:flex;align-items:center;gap:8px;color:#86909c;padding:8px 0">
              <svg class="icon" aria-hidden="true" style="font-size: 16px">
                <use xlink:href="#icon-tishi"></use>
              </svg>
              暂无快捷发起项
            </div>
          </template>
        </template>
      </div>
    </div>
    <!-- :confirmLoading="confirmLoading" -->
    <!-- :style="{ zIndex: 1 }" -->
    <a-modal
      :body-style="{ 'max-height': '750px', overflow: 'auto' }"
      :closable="false"
      :align-center="true"
      :unmount-on-close="true"
      :mask-closable="false"
      v-model:visible="visible"
      :width="952"
    >
      <div style="max-height: 80vh" class="detailShowBody">
        <ul style="display: flex; flex-wrap: wrap">
          <li
            v-for="(itm, index) in cardListData"
            :key="index"
            class="popLi"
            @click="workflowRun(itm, index)"
          >
            <svg
              v-if="itm.icon.startsWith('icon')"
              class="icon"
              aria-hidden="true"
              style="font-size: 32px"
            >
              <use :xlink:href="`#${itm.icon}`"></use>
            </svg>
            <img
              v-else
              style="width: 32px; height: 32px"
              :src="require(`@/assets/${itm.icon}.png`)"
            />
            <a-spin :loading="itm.spinning ? itm.spinning : false">
              <div
                class="ellipsis-text"
                style="padding: 0px 10px; height: 100%; margin-top: 0px"
              >
                <OverflowText :text="itm.modelName ?? ''" :maxWidth="'160px'" />
              </div>
            </a-spin>
          </li>
        </ul>
      </div>
      <template #title>
        <div class="detailShowTitle">
          <div style="display: flex; align-items: center">
            <div style="font-size: 18px">发起任务</div>
            <div
              style="
                width: 1px;
                height: 12px;
                background-color: #dedfe3;
                margin: 0px 10px;
                border-radius: 1px;
              "
            ></div>
            <div style="font-size: 14px; font-weight: 400; color: #97999c">
              说明：点击任务发起流程
            </div>
          </div>
          <div style="display: flex; align-items: center">
            <svg
              class="icon"
              style="font-size: 14px; color: #97999c; cursor: pointer"
              @click="visible = false"
              aria-hidden="true"
            >
              <use xlink:href="#icon-cuowu"></use>
            </svg>
          </div>
        </div>
      </template>
      <template style="height: 60px" #footer> </template>
    </a-modal>
    <!-- 改成流程名称 -->
    <component
      :is="nodeComponent.component"
      v-if="nodeComponent.dataObj.pageData && viewShow"
      :rawData="nodeComponent.rawData"
      :dataObj="nodeComponent.dataObj"
      ref="nodeFormUi"
      @ok="formUiRes"
      @cancel="formClose"
    >
    </component>
  </div>
</template>

<script>
import moment from "moment";
import FormRenderer from "@/components/Form/FormRenderer.vue";
import { repairUiData, repairUiruler } from "@/utils/util.js"; // 修复ui
import OverflowText from "@/views/dashboard/workplace/OverflowText.vue";
import {
  queryItemQuickList,
  queryModelView,
  processCheck as apiProcessCheck,
  processrun as apiProcessrun,
} from "@/api/workflow2";
import { saveUnlimitedValue } from "@/api/workplace";

export default {
  components: {
    FormRenderer,
    OverflowText,
  },
  name: "QuickLaunch",
  data() {
    return {
      cardListData: [],
      loading: false,
      errorMsg: '',
      visible: false,
      viewShow: false,
      sort: undefined,
      cardListDataIndex: "",
      resEd: undefined,
      nodeComponent: {
        component: "FormPreviewModal",
        rawData: {
          title: "执行",
          mode: "nodeExe",
        },
        dataObj: {},
      },
    };
  },
  created() {
    console.log('[QuickLaunch] created')
  },
  async mounted() {
    console.log('[QuickLaunch] mounted: before call')
    // const userInfo = this.$store.getters.userInfo || {}
    // const result = await this.$http.post(`/datasource/dataExec`, {
    //   'dataId': 'ds100010001573',
    //   'valueMap': {
    try {
      await this.queryCard()
      console.log('[QuickLaunch] mounted: after first call')
    } catch (e) {
      console.error('[QuickLaunch] mounted: first call error', e)
    }
    this.$nextTick(async () => {
      console.log('[QuickLaunch] mounted: nextTick before call')
      try {
        await this.queryCard()
        console.log('[QuickLaunch] mounted: nextTick after call')
      } catch (e) {
        console.error('[QuickLaunch] mounted: nextTick call error', e)
      }
    })
  },
  methods: {
    transferDate(Time) {
      return Time ? moment(parseInt(Time)).format("YYYY-MM-DD HH:mm:ss") : "";
    },
    async queryCard() {
      console.log('[QuickLaunch] queryCard trigger')
      this.loading = true
      this.errorMsg = ''
      try {
        const res = await queryItemQuickList({
          pageNo: 1,
          pageSize: 99999999,
        })
        const list = Array.isArray(res?.data)
          ? res.data
          : (Array.isArray(res?.data?.records) ? res.data.records : [])

        list.forEach((item) => {
          item.loading = false
          item.spinning = false
        })

        if (this.sort) {
          const sorted = list.slice().sort((a, b) => {
            const indexA = this.sort.indexOf(a.modelName)
            const indexB = this.sort.indexOf(b.modelName)

            const orderA = indexA === -1 ? Infinity : indexA
            const orderB = indexB === -1 ? Infinity : indexB

            return orderA - orderB
          })
          this.cardListData = sorted
        } else {
          this.cardListData = list
        }
      } catch (e) {
        console.error('[QuickLaunch] queryCard error', e)
        this.errorMsg = e?.message || '加载失败'
        this.cardListData = []
      } finally {
        this.loading = false
      }
    },
    async workflowRun(item, index) {
      // 执行流程
      this.cardListDataIndex = index;
      const { modelId, version } = item;
      this.cardListData[index].loading = true;
      this.workflowID = modelId;
      this.version = version;
      // const resultCode = await wokflowRequest(this).queryInfo({ modelId: modelId, version: version })
      try {
        const response = await queryModelView({
          // 查视图
          modelId: modelId,
          modelVersion: version,
        });
        this.viewId = response.data.viewId;
        this.resEd = response;
        let viewUi = repairUiData(
          response.data.viewUi,
          response.data.viewDataMappingDTOList
        ); // 修复ui数据源
        viewUi = repairUiruler(viewUi, response.data);
        this.nodeComponent.dataObj = viewUi;
        this.nodeComponent.rawData.updTile = response.data.viewName;
        this.viewShow = true;
        this.$nextTick(async () => {
          // 访问子组件引用并判断是否加载完成
          if (this.$refs.nodeFormUi) {
            await this.$refs["nodeFormUi"].open("nodeExe"); // 表单信息
          } else {
            console.log("Component is not loaded yet.");
          }
        });
        this.cardListData[index].loading = false;
      } catch (e) {
        this.cardListData[index].loading = false;
      }
    },
    async processrun(data) {
      // 工作流运行
      try {
        const res = await apiProcessCheck({
          ...data,
          viewId: this.viewId,
        });
        if (res.code !== 200) {
          throw new Error("验证失败");
        }
      } catch (e) {
        console.error(e);
        return;
      }
      try {
        const result = await apiProcessrun(data);
        return result;
      } catch (e) {
        this.$message.error("流程执行失败");
      } finally {
        this.cardListData[this.cardListDataIndex].loading = false;
      }
    },
    async formUiRes(modalObj, form, paramsObj, actualValue) {
      // 获取formUi提交数据
      this.$refs["nodeFormUi"].confirmLoading = true;
      try {
        const resultCode = await this.processrun({
          instanceId: "",
          modelId: this.workflowID,
          processType: "DEFAULT",
          runVariableMap: form,
          userId: "",
          version: this.version,
          serverInfoMap: {
            sponsor: {},
            tenantId: "1000",
          },
        });
        console.log(resultCode, "resultCoderesultCode");
        const { viewDataMappingDTOList, viewId } = this.resEd.data;
        const { instanceId, modelId } = resultCode.data;
        // eslint-disable-next-line no-unused-expressions
        const readUnlimitedMap = viewDataMappingDTOList
          ?.map((item) => {
            if (item.readUnlimited && actualValue[item.dataColumnKey]) {
              return {
                columnKey: item.dataColumnKey,
                instanceId: instanceId,
                taskId: modelId,
                value: actualValue[item.dataColumnKey],
                viewId: viewId,
              };
            }
          })
          .filter(Boolean);
        if (readUnlimitedMap) {
          await saveUnlimitedValue(readUnlimitedMap);
        }

        this.cardListData[this.cardListDataIndex].instanceId = instanceId;
        this.cardListData[this.cardListDataIndex].loading = false;
        this.cardListData[this.cardListDataIndex]["spinning"] = false;
        this.viewShow = false;
        this.nodeComponent.dataObj = false;
        this.$refs["nodeFormUi"].confirmLoading = false;
        this.$message.success("操作成功！");
        this.$refs["nodeFormUi"].close();
        this.visible = false;
      } catch (e) {
        console.log("报错：", e);
        this.$refs["nodeFormUi"].confirmLoading = false;
      }
    },
    async formClose() {
      // 关闭后触发
      this.cardListData[this.cardListDataIndex]["spinning"] = false;
      this.viewShow = false;
    },
  },
};
</script>

<style lang="less" scoped>
.title {
  background-color: #ffffff;
  border-radius: 5px;
  padding: 10px;
  margin: 10px 0px;
}

ul {
  justify-content: flex-start;
  display: flex;
  // justify-content: space-between;
  list-style: none; /* 去掉默认的圆点 */
  padding: 0; /* 去掉内边距 */
  margin: 0; /* 去掉外边距 */
}

li {
  display: flex;
  margin: 10px;
}

.ellipsis-text {
  display: flex;
  align-items: center; /* 垂直居中 */
  text-align: center; /* 文本内容居中对齐 */
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
  margin-top: -10px;
  color: #222b3c;
  font-size: 14px;
  font-weight: 500;
  width: 135px; /* 根据需求调整宽度 */
  height: 50px; /* 容器高度 */
  padding: 10px; /* 内边距保证文字不靠边 */
}

.card {
  width: 12%;
  margin: 10px 0px;
  border-radius: 10px;
  padding: 0px 0px;
  text-align: center;
  cursor: pointer;
}
.card:hover {
  border: 1px solid #1890ff; /* 悬停时添加边框 */
}
.divCard {
  flex-wrap: wrap;
  display: flex;
  gap: 0px 30px; /* 定义网格项之间的间隔 */
}
.ant-card-body {
  padding: 0px;
}

:deep(.arco-modal .arco-modal-content) {
  border-radius: 16px;
  box-shadow: 0px 0px 18px 0px rgba(171, 186, 204, 0.5);
}

:deep(.arco-modal .arco-modal-header) {
  padding: 0px;
  border-radius: 16px 16px 0px 0px;
  border-bottom: none;
}

:deep(.arco-modal .arco-modal-body) {
  padding: 0px;
}

:deep(.arco-modal .arco-modal-footer) {
  padding: 0px;
  border-top: none;
}

.detailShowTitle {
  height: 54px;
  border-radius: 16px 16px 0px 0px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 24px;
  // background: linear-gradient( 180deg, #DBEBFF 0%, #FFFFFF 100%);
}

.detailShowBody {
  padding: 4px 24px 24px;
  overflow-y: scroll;
  background: #f4f8ff;
  border-radius: 0px 0px 16px 16px;
}

.popLi {
  border-radius: 6px;
  cursor: pointer;
  width: 204px;
  background: #ffffff;
  padding: 10px;
  align-items: center;
  box-shadow: 0px 0px 2px 0px rgba(219, 222, 230, 0.5);
}
.popLi:hover {
  box-shadow: 0 0 0 1px #2983ff;
}
</style>
